package com.example.singleReactorSingleThread;


import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;
import java.util.Set;

public class Reactor implements Runnable{

    private Selector selector;

    public Reactor(int port){
        try {
            selector = Selector.open();
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            serverSocketChannel.configureBlocking(false);
            serverSocketChannel.bind(new InetSocketAddress(port));
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT,new Acceptor(serverSocketChannel,selector));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void run() {
        while (!Thread.interrupted()){
            try {
                selector.select();
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()){
                    SelectionKey selectionKey = iterator.next();
                    process(selectionKey);
                    iterator.remove();
                }
            }catch (Exception e){

            }

        }
    }

    private void process(SelectionKey selectionKey){
        Runnable runnable = (Runnable)selectionKey.attachment();
        if (runnable instanceof Handler){
            Handler handler = (Handler)runnable;
            handler.setSelectionKey(selectionKey);
        }
        runnable.run();
    }
}
